package com.project.serviceImpl;

//导入服务接口

import acl.RegisterService;
import com.Entity.*;
import com.alibaba.dubbo.config.annotation.Service;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.project.repositoryImpl.*;
import com.project.util.alibaba.AlibabaMainUtil;
import com.project.util.baseUtil.HospitalUtil;
import com.project.util.redis.RedisUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Service(interfaceClass = RegisterService.class)
@org.springframework.stereotype.Service
@Transactional
public class RregisterServiceImpl implements RegisterService {

    Logger log = Logger.getLogger("RregisterServiceImpl");

    @Resource
    private RabbitTemplate rt;

    @Resource
    private RepositoryDzmHisHospitalImpl repositoryDzmHisHospital;

    @Resource
    private RepositoryDzmHisDepartmentImpl repositoryDzmHisDepartment;

    @Resource
    private RepositoryDzmHisClinicImpl  repositoryDzmHisClinic;

    @Resource
    private RepositoryDzmHisDoctorImpl repositoryDzmHisDoctor;

    @Resource
    private RepositoryDzmHisSchedulingImpl repositoryDzmHisScheduling;


    @Resource
    private  RepositoryDzmHisRegistrationImpl repositoryDzmHisRegistration;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayTradeWapPayRequest payRequest;

    @Resource
    private AlipayTradeAppPayModel aliModel;

    @Override
    /**
     * 把医院信息放入缓存
     */
    /*@Cacheable(keyGenerator = "wiselyKeyGenerator",cacheNames = "weather")*/
    /**
     * Description: <br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 7:57<br/>
     * @param:[]<br/>
     * @return:java.util.List<com.Entity.DzmHisHospitalEntity>
     */
    public List<DzmHisHospitalEntity> getHospital() {
        return repositoryDzmHisHospital.findAll();
    }

    
    @Override
    /*@Cacheable("#root.methodName")*/
    /**
     * Description: <br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 7:57<br/>
     * @param:[hid]  医院id<br/>
     * @return:java.util.List<com.Entity.DzmHisDepartmentEntity>
     */
    public List<DzmHisDepartmentEntity> getFaculty(Integer hid) {
        List<DzmHisDepartmentEntity> list = repositoryDzmHisDepartment.findByHid(hid);
        return list;
    }

    /**
     *  门诊信息
     */
    @Override
    /**
     * Description: <br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 7:58<br/>
     * @param:[]<br/>
     * @return:java.util.List<com.Entity.DzmHisClinicEntity>
     */
    public List<DzmHisClinicEntity> getClinics() {
        return repositoryDzmHisClinic.findAll();
    }

    @Override
    /**
     * Description: <br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 8:50<br/>
     * @param:[hid, did]<br/>
     * @return:java.util.List<java.util.Map<java.lang.String,java.lang.String>>
     */
    public List<Map<String,Object>> gethospitalDoctors(String hid,String did) {
        return repositoryDzmHisDoctor.gethospitalDoctors(hid,did);
    }

    @Override
    /**
     * Description: <br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 14:19<br/>
     * @param:[doctor_id]<br/>
     * @return:com.Entity.DzmHisDoctorEntity
     */
    public DzmHisDoctorEntity getDoctorInfo(Integer doctor_id) {
        return repositoryDzmHisDoctor.queryDoctorInfo(doctor_id);
    }

    @Override
    /**
     * Description: 查询出该医生的排班信息<br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 15:35<br/>
     * @param:[map : 有医生id  doctor_id  科室id did   门诊id  cid]<br/>
     * @return:
     */
    @Cacheable(keyGenerator = "wiselyKeyGenerator",cacheNames = "weather")
    public List<Map<String,String>> getSchedulingInfo(Map<String,String> map){
        return  repositoryDzmHisScheduling.getSchedulingInfo(map.get("doctor_id"),map.get("cid"),map.get("did"));
    }
    /**
     * Description: 查询出不同时间的医生排班<br/>
     * @author: lenovo<br/>
     * @date: 2019/1/2 9:37<br/>
     * @param:<br/>
     * @return:
     */
    @Override
    /*@Cacheable(keyGenerator = "wiselyKeyGenerator",cacheNames = "weather")*/
    public List<Map<String, Object>> getScheduling(Map<String, String> map) {
        return  repositoryDzmHisScheduling.getScheduling(map.get("doctor_id"),map.get("cid"),map.get("did"),map.get("date"));
    }

    /**
     * Description: 查出某天内所有排班信息<br/>
     * @author: lenovo<br/>
     * @date: 2019/1/2 10:40<br/>
     * @param:<br/>
     * @return:
     */
    @Override
    /*@Cacheable(keyGenerator = "wiselyKeyGenerator",cacheNames = "weather")*/
    public List<Map<String, Object>> getAllNowDector(Map<String, String> map) {
        return repositoryDzmHisScheduling.getAllNowDector(map.get("cid"),map.get("did"),map.get("date") );
    }

    /**
     * Description: 通过排班id查出所有数据<br/>
     * @author: lenovo<br/>
     * @date: 2019/1/3 8:34<br/>
     * @param:<br/>
     * @return:
     */
    @Override
    /*@Cacheable(keyGenerator = "wiselyKeyGenerator",cacheNames = "weather")*/
    public Map<String,Object> getChooseInfo(String scheduling_week_id) {

        Map<String,Object> chooseInfo = repositoryDzmHisScheduling.getChooseInfo(scheduling_week_id);

        log.info(HospitalUtil.classify(chooseInfo));
        //在订单生成之前判断  医生可挂号人数是否还够
        final Long classifySize = RedisUtil.size(HospitalUtil.classify(chooseInfo));//redis 中取出 排队队列
        Map<String,Object> chooseInfos  = new HashMap<>();
        chooseInfos.putAll(chooseInfo);
        if (classifySize >= HospitalUtil.classifySize){//判断列表是否满员
            chooseInfos.put("sorry","sorry");
        }else {
            chooseInfos.put("sorry","");
        }
        return chooseInfos;
    }

    @Override
    public String orderGeneration(String scheduling_week_id) {
        boolean flg = true;
        String massage = "";

        Map<String,Object> map = repositoryDzmHisScheduling.getChooseInfo(scheduling_week_id);

        DzmHisRegistrationEntity entity = new DzmHisRegistrationEntity();
        try {
            entity.setPhysicianId(Integer.parseInt(map.get("physicianid")+""));
            entity.setCompanyId(Integer.parseInt(map.get("company_id")+""));
            entity.setDepartmentId(Integer.parseInt(map.get("department_id")+""));
            entity.setRegisteredfeeId(Integer.parseInt(map.get("registeredfee_id")+""));
            entity.setRegistrationAmount(Double.parseDouble(map.get("registeredfee_aggregate_amount")+""));
            entity.setSchedulingSubsectionId(Integer.parseInt(map.get("scheduling_subsection_id")+""));
            entity.setSchedulingId(Integer.parseInt(map.get("scheduling_id")+""));
            entity.setSchedulingWeekId(Integer.parseInt(map.get("scheduling_week_id")+""));
            entity.setRegistrationStatus((byte)5);//生成订单时状态默认为5：未支付
            entity.setPatientId(1);//患者id
            /*entity.setCreateTime(System.currentTimeMillis()/1000);*/
            entity = repositoryDzmHisRegistration.save(entity);
            log.info("测试++++++++++"+entity.toString());
        }catch (Exception e){
            flg = false;
            e.printStackTrace();
        }
        if (flg){
            massage = "success";
            rt.convertAndSend("payExchange","pay.register.project",entity);

            /**
             * 配置支付回调地址
             */
            payRequest.setReturnUrl(AlibabaMainUtil.return_url);
            payRequest.setNotifyUrl(AlibabaMainUtil.notify_url);

            /**
             * 配置参数
             */
            aliModel.setBody("(挂号)");//对商品的描述
            aliModel.setTotalAmount(entity.getRegistrationAmount()+"");//商品金额
            aliModel.setProductCode("QUICK_MSECURITY_PAY");//销售产品码
            aliModel.setSubject("挂号费用id"+entity.getRegisteredfeeId());//商品名称
            aliModel.setOutTradeNo(entity.getRegistrationId()+"");//商户订单号

            payRequest.setBizModel(aliModel);

            String from = "";

            try {
                from  = alipayClient.pageExecute(payRequest).getBody();
                if(!from.equals("err") ){
                    massage = from;
                    log.info(massage);
                }
            }catch (Exception e){
                log.info("调用ali支付失败");
                e.printStackTrace();
            }
        }else {
            massage = "error";
        }
        /**
         * 将挂号订单id信息放入redis
         */
        log.info(HospitalUtil.classify(map));
        RedisUtil.right(HospitalUtil.classify(map),entity.getRegistrationId());
        return massage;
    }
}
